<template>
  <view class="padding-lg bg-gray" style="min-height:100vh">

    <view class="margin-top bg-cus-blue" style="border-radius:10px">
      <view class="padding text-center text-xl text-white">预约核酸项目</view>

      <view class="bg-white padding" style="border-radius:5px">
        <evan-form :hide-required-asterisk="false" :label-style="labelStyles" 
          ref="form" :model="formInfo" class="no-bottom-border">

          <evan-form-item label="预约日期" prop="date" label-position="top" class="margin-top">
            <i-calendar 
              style="width:100%"
              :brief="false"
              :date="nowDate"
              :start-date="calendarStartDate"
              :end-date="calendarEndDate"
              @change="onCalendarChange"
              />
          </evan-form-item>

          <evan-form-item label="预约时段" prop="timeRange" label-position="top" class="margin-top">
            <radio-group style="width:100%" class="grid col-3">
              <view class="padding-xs" v-for="(it, i) in timeRangeOpts" :key="it.inx">
                <label>
                  <!-- TODO: -->
                  <button class="btn-cus-mini" size="mini" 
                    :disabled="!isTimeRangeValid(it)"
                    @click="onClickTimeRange(it)" 
                    :type="it.inx === formInfo.timeRange ? 'primary' : 'default'">{{it.range}}</button>
                  <view class="visibility-hidden">
                    <radio :value="it.inx" :checked="it.inx === formInfo.timeRange" />
                  </view>
                </label>
              </view>
            </radio-group>
          </evan-form-item>
          <view class="text-red text-sm">
            <text>当前时段已预约</text>
            <text class="margin-lr-xs">{{yuyueCount}}</text>
            <text>人</text>
          </view>

          <evan-form-item label="预约项目" prop="item" label-position="top" class="margin-top">
            <radio-group @change="onItemChange" style="width:100%">
              <label class="flex justify-between align-center padding-tb-xs" v-for="(it, i) in items" :key="it.item_id">
                <view style="flex:1">
                  {{it.item_name}}
                </view>
                <view class="padding-lr-xs text-right text-gray" style="width:80px">
                  {{it.type_name}}
                </view>
                <view class="padding-lr-xs text-right text-red" style="width:60px">
                  {{it.price}}元
                </view>
                <view class="padding-lr-xs">
                  <radio :value="it.item_id" :checked="it.item_id === formInfo.item" />
                </view>
              </label>
            </radio-group>
          </evan-form-item>

          <view class="margin-top-xl">
            <button :disabled="submiting" @click="onSubmit" class="cu-btn lg btn-fluid bg-primary">确认预约</button>
          </view>
        </evan-form>
      </view>
    </view>
    
    <cu-bar></cu-bar>
  </view>
</template>

<script>
import moment from 'moment'
import iCalendar from '@/components/i-calendar/i-calendar.vue'
import CheckAuthMixin from '@/mixins/CheckAuthMixin'
import PayMixin from '@/mixins/PayMixin'
import checkIdCard from '@/libs/checkIdCard' 

const CACHE_KEY = 'ts_matters_submiting'

const FormInfo = {
  item: '', // 收费项目
  timeRange: '', // 时间
  date: '', // 日期
}

export default {
  mixins: [
    CheckAuthMixin,
    PayMixin,
  ],
  components: {
    iCalendar,
  },
  data() {
    const twoDigits = (n) => {
      return n < 10 ? `0${n}` : '' + n
    }
    
    return {
      /**
       * FIXME:
       */
      userInfo: {},
      labelStyles: {
        minWidth: '80px',
        textAlign: 'justify',
        paddingRight: '30upx',
        fontSize: '30upx',
        color: 'inherit',
      },
      submiting: false,
      nowDate: moment().format('YYYY-MM-DD'),
      nowTime: moment().format('HH:mm'),
      formInfo: Object.assign({}, FormInfo),
      formRules: {
        date: [
          { required: true, message: '请选择预约日期' },
        ],
        timeRange: [
          { required: true, message: '请选择预约时段' },
        ],
        item: [
          { required: true, message: '请选择预约项目' },
        ],
      },

      items: [
      ],
      timeRangeOpts: [],
      yuyueCount: 0,
    }
  },
  watch: {
    submiting(val) {
      if (val) {
        uni.showLoading()
      } else {
        uni.hideLoading()
      }
    },
  },
  computed: {
    calendarStartDate() {
      return moment().format('YYYY-MM-DD')
    },
    calendarEndDate() {
      return moment().add(30, 'days').format('YYYY-MM-DD')
    },
  },
  onLoad(opts) {
    

    /**
     * FIXME:
     */
    this.formInfo.date = this.nowDate

    this.loadState()
  },
  mounted() {
    this.$refs.form.setRules(this.formRules)

    // this.initPay()
    this.getTimeRangeOpts1()
  },
  methods: {
    // getItems() {
    //   /**
    //    * 获取检验项目
    //    */
    //   this.$http({
    //     url: '/api/CheckItem/GetAll',
    //     method: 'POST',
    //     success: (res) => {
    //       if (res.success) {
    //         this.items = res.data.map(x => {
    //           const {
    //             item_id, //: "12435"
    //             item_name, //: "新冠病毒核酸检测（常规）"
    //             price, //: 19.7
    //             type_id, //: 1
    //             type_name, //: "1:1（单人单管）"
    //           } = x
    //           return {
    //             item_id: item_id + '',
    //             item_name,
    //             price,
    //             type_id,
    //             type_name,
    //           }
    //         })

    //         if (this.items.length > 0) {
    //           this.formInfo.item = this.items[0].item_id
    //           this.onItemChange()
    //         }
    //       }
    //     }
    //   })
    // },
    getItems1() {
      this.formInfo.item = ''

      const range = this.timeRangeOpts.find(x => x.inx == this.formInfo.timeRange)
      /**
       * 获取检验项目
       */
      this.$http({
        url: `/api/CheckItem/GetAll?range=${range.range}`,
        method: 'POST',
        success: (res) => {
          if (res.success) {
            this.items = res.data.map(x => {
              const {
                item_id, //: "12435"
                item_name, //: "新冠病毒核酸检测（常规）"
                price, //: 19.7
                type_id, //: 1
                type_name, //: "1:1（单人单管）"
                range_id,
                max_num,
              } = x
              return {
                item_id: item_id + '',
                item_name,
                price,
                type_id,
                type_name,
                range_id,
                max_num,
              }
            })

            if (this.items.length > 0) {
              this.formInfo.item = this.items[0].item_id
              this.onItemChange()
            }
          }
        }
      })
    },
    onClickTimeRange(it) {
      this.formInfo.timeRange = it.inx
      this.getItems1()
      
      /**
       * 查询时段内已预约人数
       */
      const range = this.timeRangeOpts.find(x => x.inx == this.formInfo.timeRange)
      this.$http({
        url: '/api/Book/QueryCount',
        method: 'POST',
        data: {
          appo_date: this.formInfo.date,
          range: range.range,
        },
        success: (res) => {
          if (res.success) {
            this.yuyueCount = res.data
          }
        }
      })
    },
    isTimeRangeValid(it) {
      if (this.formInfo.date == this.nowDate) {
        return this.nowTime < it.range.split('-')[1]
      } else {
        return true
      }
    },
    // getTimeRangeOpts(typeId) {
    //   /**
    //    * 根据类别Id查询时间段
    //    */
    //   this.$http({
    //     url: `/api/TimeRange/QueryByCheckType?type_id=${typeId}`,
    //     method: 'POST',
    //     success: (res) => {
    //       if (res.success) {
    //         this.timeRangeOpts = res.data.map(x => {
    //           const {
    //             max_num, //: 999
    //             range, //: "08:00-09:00"
    //             range_id, //: 2
    //             status, //: "0"
    //             type_id, //: 1
    //           } = x
    //           return {
    //             range_id: range_id + '',
    //             range,
    //             status,
    //             max_num,
    //             type_id,
    //           }
    //         })
    //       }
    //     }
    //   })
    // },
    getTimeRangeOpts1() {
      /**
       * 根据类别Id查询时间段
       */
      this.$http({
        url: `/api/TimeRange/GetAll`,
        method: 'POST',
        success: (res) => {
          if (res.success) {
            this.timeRangeOpts = res.data.map((x,i) => {
              return {
                inx: '' + i,
                range: x,
              }
            })
          }
        }
      })
    },
    fmtDate(dateStr, fmt) {
      return moment(dateStr).format(fmt || 'YYYY-MM-DD')
    },
    onCalendarChange(e) {
      this.formInfo.date = e.fulldate
    },
    onItemChange(e) {
      if (e) {
        this.formInfo.item = e.detail.value
      }
      // const item = this.items.find(x => x.item_id == this.formInfo.item)
      // this.formInfo.timeRange = ''
      // this.getTimeRangeOpts(item.type_id)
    },
    onSubmit() {
      this.$refs.form.validate((res) => {
        if (res) {
          this.$utils.pLog('== submiting: ', this.formInfo)

          const { pat_id } = this.userInfo
          const { date, item: item_id, timeRange } = this.formInfo
          const item = this.items.find(x => x.item_id == item_id)
          const { type_id, range_id } = item

          /**
           * 预约
           */
          this.$http({
            url: '/api/Book/Create',
            method: 'POST',
            data: {
              pat_id, // "": 0,
              appo_date: date, // "": "2022-05-13T00:57:01.002Z",
              range_id, // "": 0,
              item_id, // "": "string",
              type_id, // "": 0
            },
            success: (res) => {
              if (res.success) {
                const orderId = res.data
                
                uni.showToast({
                  title: '预约成功'
                })
                setTimeout(() => {
                  this.gotoPay(orderId)
                }, 1500)
              } else {
                uni.showToast({
                  title: res.msg,
                  icon: 'none'
                })
              }
            }
          })
        }
      })
    },
    saveState() {
      // this.$utils.tempPageData.set(this.formInfo, CACHE_KEY)
    },
    loadState() {
      const cached = this.$utils.tempPageData.get(CACHE_KEY)
      if (cached) {
        this.userInfo = cached
        this.$utils.pLog('== user info: ', this.userInfo)
      }
    },
  },
}
</script>

<style scoped>
.bg-cus-blue {
  background: #3182F8;
}
.no-bottom-border /deep/ .evan-form-item-container {
  border-bottom: none;
}
.visibility-hidden {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  z-index: -1;
}
.btn-cus-mini {
  width: 100%;
  text-align: center;
  padding-left: 0;
  padding-right: 0;
  box-sizing: border-box;
}
</style>